import time
import os
import paramiko
import base64
import threading
from datetime import datetime
import socket
import encodings.idna

log_=False
thread_=''
threading_List=[]
successful_=['\n\n']
AuthenticationException_=['\n']
NoValidConnectionsError_=['\n']
SSHException_=['\n']
timeout_=['\n']
e_=['\n']
time2=str(datetime.now())
path=os.path.dirname(os.path.abspath(__file__))

class SSH():#连接模块
    def __init__(self,ip,port,username,password):
        self.ip=ip
        self.port=port
        self.username=username
        self.password=password
    def test(self):
        #trans=paramiko.Transport((ip,port))
        #trans.connect(username=self.username,password=self.password)
        
        Chanenel=paramiko.SSHClient()
        #ssh._transport=trans
        Chanenel.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        try:
            Chanenel.connect(hostname=self.ip,
                    username=self.username,
                    port=self.port,
                    password=self.password,
                    look_for_keys=False,
                    timeout=2,
                    allow_agent=False)
            ssh=Chanenel.invoke_shell()
            str=self.ip+' 连接成功#'+'\n'
            print(str)
            str2=self.ip+' 操作成功'+'\n'
            log_=execut(ssh)
            successful_.append(str2)
            log_write(log_)
        except paramiko.ssh_exception.AuthenticationException:
            str=self.ip+' 密码错误'+'\n'
            print(str)
            AuthenticationException_.append(str)
        except paramiko.ssh_exception.NoValidConnectionsError:
            str=self.ip+' 连接错误(主机不存在或者网络问题等)'+'\n'
            print(str)
            NoValidConnectionsError_.append(str)
        except paramiko.ssh_exception.SSHException:
            str=self.ip+' 远程主机强迫关闭了一个现有的连接'+'\n'
            print(str)
            SSHException_.append(str)
        except (TimeoutError,socket.timeout):
            str=self.ip+' 连接超时'+'\n'
            print(str)
            timeout_.append(str)
        except:
            global log
            global thread__
            log_=False
            thread_=''
            str=self.ip+' 未知错误'+'\n'
            print(str)
            e_.append(str)
        #print(threading.current_thread().name)
    def run(self):
        thread=threading.Thread(target=self.test)
        threading_List.append(thread)
        #self.test()

def execut(ssh):#下发指令
    f=open(path+r'/order.txt','r')
    for i in f.readlines():
        print(i,end='')
        #ssh_stdin,ssh_stdout,ssh_stderr=ssh.exec_command(i)
        #print(stdout.read())
        ssh.send(i+'\n')
        time.sleep(0.5)
        global log_
        global thread_
        if log_ == False:
            thread_=threading.current_thread().name
            log_=True
    return_=''        
    if thread_ == threading.current_thread().name:
        return_=ssh.recv(5000).decode('utf-8')
    ssh.close()
    return return_

def decode(str): #密码解密读入
    str=base64.b64decode(str)
    str=str.decode('utf-8')
    x=len(str)
    x=int((x-9)/2)
    result=''
    for i in range(x):
        result+=str[i]
    return result[::-1]

def log_write(x):#输出日志
    if not os.path.exists(path+r'/log/'):
        os.mkdir(path+r'/log')
    time1=time2.split()
    f=open(path+r'/log/'+time1[0][5:7]+time1[0][8:10]+time1[1][0:2]+time1[1][3:5]+'.log','a')
    #f.write(time1[0]+'-'+time1[1][0:8]+'\n')
    f.write(x)
    f.close()

def log_error(x):#错误日志
    if not os.path.exists(path+r'/log/'):
        os.mkdir(path+r'/log')
    time1=time2.split()
    f=open(path+r'/log/'+time1[0][5:7]+time1[0][8:10]+time1[1][0:2]+time1[1][3:5]+'.log','a')
    for i in x:
        f.write(i)
    f.close()    

if __name__=='__main__':
    if not os.path.exists(path+r'/order.txt'):
        print('order.txt不存在')
        exit(0)
    if not os.path.exists(path+r'/ip.txt'):
        print('ip.txt不存在')
        exit(0)
    f=open(path+r'/ip.txt','r')
    for i in f.readlines():
        i=i.split()
        ip=i[0]
        port=int(i[1])
        username=i[2]
        password=i[3]
        password=decode(password)
        ssh=SSH(ip,port,username,password)
        ssh.run()
    f.close()
    for i in threading_List:
        i.start()
    for i in threading_List:
        i.join()
    log_error(successful_)
    log_error(AuthenticationException_)
    log_error(NoValidConnectionsError_)
    log_error(SSHException_)
    log_error(timeout_)
    log_error(e_)
